'use strict';
const db = uniCloud.database();
const table = 'announcement';
const dbCmd = db.command
const $ = db.command.aggregate
const uniID = require('uni-id')


exports.main = async (event, context) => {

	// 云函数url，把body转为event所需
	let body = event.body
	if (body) {
		let token = event.headers.uniidtoken
		if (event.isBase64Encoded) {
			body = Buffer.from(body)
		}
		const param = JSON.parse(body) // param为客户端上传的数据
		if (param) {
			event = param
			event.uniIdToken = token
		}
	}

	let params = event.params || {}
	const action = event.cloudAction
	let payload = {}
	let noCheckAction = ['getListByIds', 'index', 'show', 'my', 'list'] //白名单，无需校验token

	if (noCheckAction.indexOf(action) === -1) {
		if (!event.uniIdToken) {
			return {
				code: 403,
				msg: '缺少token'
			}
		}
		payload = await uniID.checkToken(event.uniIdToken) // 校验token
		if (payload.code && payload.code > 0) {
			return payload
		}
		params.uid = payload.uid
	}

	switch (action) {
		// 获取列表数据
		case "index":
			var size = await db.collection(table).aggregate()

				.lookup({
					from: 'uni-id-users',
					localField: 'userid',
					foreignField: '_id',
					as: 'userInfo',
				})
				.match({
					userInfo: {
						username: params.username === '' ? dbCmd.gte(params.username) : dbCmd.eq(params
							.username)
					}
				})
				.count('total')
				.end()

			// 列表数据
			var res = await db.collection(table).aggregate()

				// 1为审核通过
				.match({
					status: dbCmd.eq(1)
				})
				.lookup({
					from: 'uni-id-users',
					localField: 'userid',
					foreignField: '_id',
					as: 'userInfo',
				})
				.match({
					userInfo: {
						username: params.username === '' ? dbCmd.gte(params.username) : dbCmd.eq(params
							.username)
					}
				})
				.sort({
					_id: -1
				})
				.skip(params.start)
				.limit(params.limit)
				.end()
			console.log('res', res)
			return {
				code: 0,
					data: {
						list: res.data,
						total: size.data.length === 0 ? 0 : size.data[0].total
					}
			};
			break;


		case "list":
			var collection = db.collection(table)
			console.log(params)
			var res = await collection
				.where({
					status: dbCmd.eq(0).or(dbCmd.eq(1)),
				})
				// dbCmd.set({
				// 	status: dbCmd.eq(0).or(dbCmd.eq(1)),
				// 	address: params.limit,
				// 	type: params.type,
				// 	money: params.money || '',
				// })
				.orderBy("_id", "desc")
				.skip(params.start)
				.limit(params.limit)
				.get();
			return {
				error: 0,
					data: {
						list: res.data
					}
			};
			break;
		case "show":
			var id = params.id;
			var collection = db.collection(table)
			var res = await collection.where({
				_id: id
			}).limit(1).get();
			//获取作者
			var userid = res.data[0].userid;
			var tb_user = db.collection("uni-id-users");
			var user = await tb_user.where({
				_id: userid
			}).limit(1).get();
			return {
				error: 0,
					data: {
						data: res.data[0],
						user: user.data[0]
					},
			};
			break;
		case "my":
			var collection = db.collection(table)
			var res = await collection.where({
					userid: params.ssuserid
				})
				.orderBy("_id", "desc")
				.skip(params.start)
				.limit(params.limit)
				.get();
			return {
				error: 0,
					data: {
						list: res.data
					}
			};
			break;
			// 审核帖子
		case "all":
			var collection = db.collection(table)
			var res = await collection
				// .where({
				// 	userid:params.ssuserid
				// })
				.orderBy("_id", "desc")
				.skip(params.start)
				.limit(params.limit)
				.get();
			return {
				error: 0,
					data: {
						list: res.data
					}
			};
			break;
			// 查看列表
		case "add":
			var id = params.id;
			var uname = params.uname;
			var collection = db.collection(table)
			var res = await collection.where({
				_id: id
			}).limit(1).get();
			var userid = params.ssuserid;
			delete params.ssuserid;
			if (res.data.length < 1) {
				return {
					error: 1,
					message: "数据不存在"
				}
			}
			if (res.data[0].userid != userid) {
				return {
					error: 1,
					message: "您无权限"
				}
			}
			return {
				error: 0,
					data: res,
			};

			break;

			// 管理员查询
		case "add2":
			var id = params.id;
			var uname = params.uname;
			var collection = db.collection(table)
			var res = await collection.where({
				_id: id
			}).limit(1).get();
			var userid = params.ssuserid;
			delete params.ssuserid;

			if (res.data.length < 1) {
				return {
					error: 1,
					message: "数据不存在"
				}
			}

			return {
				error: 0,
					data: res,
			};
			break;
			// 发布图片
		case "save":
			var collection = db.collection(table)
			if (params._id != undefined) {
				var _id = params._id;
				delete params._id;
				var userid = params.ssuserid;

				var row = await collection.where({
					_id: _id
				}).limit(1).get();

				if (row.data.length < 1) {
					return {
						error: 1,
						message: "数据不存在"
					}
				}
				if (row.data[0].userid != userid) {
					return {
						error: 1,
						message: "您无权限"
					}
				}
				var res = await collection.doc(_id).update(params)
			} else {
				var res = await collection.add(params)
			}
			return {
				error: 0,
					data: res,
			};
			break;
			// 管理员修改
		case "save2":
			var collection = db.collection(table)
			if (params._id != undefined) {
				var _id = params._id;
				delete params._id;
				var userid = params.ssuserid;

				var row = await collection.where({
					_id: _id
				}).limit(1).get();

				if (row.data.length < 1) {
					return {
						error: 1,
						message: "数据不存在"
					}
				}
				var res = await collection.doc(_id).update(params)
			} else {
				var res = await collection.add(params)
			}

			return {
				error: 0,
					data: res,
			};
			break;
		case "delete":
			var id = params.id;
			var collection = db.collection(table)
			var res = await collection.doc(id).remove();
			return {
				error: 0,
					data: "success",
			};
			break;
		case "addView":
			var _id = params.id;
			var collection = db.collection(table)
			var row = await collection.where({
				_id: _id
			}).limit(1).get();

			if (row.data.length < 1) {
				return {
					error: 1,
					message: "数据不存在"
				}
			}
			if (row.data[0].view_num == undefined) {
				var view_num = 1;
			} else {
				var view_num = row.data[0].view_num + 1;
			}
			var res = await collection.doc(_id).update({
				view_num: view_num
			})
			return {
				error: 0,
					data: "success",
			};
			break;
		case "getListByIds":
			if (params.ids.length == 0) {
				return {
					error: 1,
					message: "无数据"
				}
			}
			var tb = db.collection(table);
			var res = await tb.where({
				_id: dbCmd.in(params.ids)
			}).get();
			return {
				error: 0,
					data: res.data
			}
			break;
		case "follow":
			// 列表数据
			var res = await db.collection(table)
				.aggregate()
				.match({
					status: dbCmd.eq(1)
				})
				// 1为审核通过
				.lookup({
					from: 'fans',
					localField: 'uid',
					foreignField: 'bloggerId',
					as: 'userInfos',
				})
				.match({
					userInfos: {
						fansId: params.id,
					}
				})
				.match({
					status: dbCmd.eq(1)
				})
				.lookup({
					from: 'uni-id-users',
					localField: 'uid',
					foreignField: '_id',
					as: 'userInfo',
				})
				.match({
					userInfo: {
						username: params.username === '' ? dbCmd.gte(params.username) : dbCmd.eq(params
							.username)
					}
				})
				.sort({
					_id: -1
				})
				.skip(params.start)
				.limit(params.limit)
				.end()
			console.log('res', res)
			return {
				code: 0,
					data: {
						list: res.data,
						total: res.data.length === 0 ? 0 : res.data[0].total
					}
			};
			break;
		default:
			return {
				code: 403,
					msg: '非法访问'
			}
			break;
	}
};
